package com.example.goodtrash.search;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.goodtrash.FileUtil.Base64Util;
import com.example.goodtrash.FileUtil.FileUtil;
import com.example.goodtrash.R;
import com.example.goodtrash.model.Result;
import com.example.goodtrash.model.Trash;
import com.example.goodtrash.util.HttpUtil;
import com.example.goodtrash.util.Utility;
import com.google.android.material.appbar.MaterialToolbar;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class imageSearch extends AppCompatActivity {
   private ImageView ivPicture;
    private List<Trash> dataList=new ArrayList<>();
    private TrashAdapter adapter;
    private RecyclerView rvResult;
    private ProgressDialog progressDialog;
    private MaterialToolbar toolbar;
    private File outputImage;
    private static final int REQUEST_CODE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE","android.permission.CAMERA"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_search);
        Button album=findViewById(R.id.btn_open_album);
        Button photo=findViewById(R.id.btn_take_photo);
        ivPicture=findViewById(R.id.iv_picture);
        rvResult=findViewById(R.id.rv_classification_result);
        toolbar=findViewById(R.id.toolbar);
        adapter=new TrashAdapter(dataList,imageSearch.this,imageSearch.this);
        rvResult.setLayoutManager(new LinearLayoutManager(this));
        rvResult.setAdapter(adapter);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //未赋予权限，申请权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                //选择不开启权限的时候，提示用户
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);

        } else {
            //权限已赋予
            Toast.makeText(this, "已授权成功！", Toast.LENGTH_SHORT).show();
        }


        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                turnOnCamera();
            }
        });
        album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openAlbum();
            }
        });

    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }

    @SuppressLint("LongLogTag")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2 &&resultCode == RESULT_OK){
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            final Uri imageUri = Objects.requireNonNull(data).getData();
            Cursor cursor = getContentResolver().query(imageUri, filePathColumns, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
            //获取图片路径
            String imagePath = cursor.getString(columnIndex);
            cursor.close();
            //识别
            localImageDiscern(imagePath);
        } else if(requestCode == 3 ){
            String imagePath = outputImage.getAbsolutePath();
            localImageDiscern(imagePath);
        }else {Toast.makeText(imageSearch.this,"不行",Toast.LENGTH_SHORT).show();}

    }

    @SuppressLint("LongLogTag")
    private void localImageDiscern(String imagePath){
        try {
                Glide.with(imageSearch.this).load(imagePath).into(ivPicture);
                ivPicture.setVisibility(View.VISIBLE);

            //按字节读取文件
            byte[]  imgData = FileUtil.readFileByBytes(imagePath);

            //字节转Base64
            String imageBase64 = Base64Util.encode(imgData);
            showLoadingDialog();
            queryImage(imageBase64);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void showLoadingDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(imageSearch.this);
            progressDialog.setMessage("正在加载.....");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }


    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }
    private void queryImage(String imageBase64){
        HttpUtil.sendImageRequest(imageBase64, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                closeProgressDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(imageSearch.this,"搜索失败",Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseText=response.body().string();
                Result result= Utility.handleImageResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(result!=null&&"success".equals(result.getMessage())){
                         closeProgressDialog();

                            dataList.clear();
                            List<Trash> trashList=result.getTrashList();
                            for(Trash trash: trashList) {
                                dataList.add(trash);
                            }
                            adapter.notifyDataSetChanged();

                        }else if("No match result".equals(result.getMessage())){
                            closeProgressDialog();
                            Toast.makeText(imageSearch.this,"搜索到知识盲区啦",Toast.LENGTH_SHORT).show();
                        } else if ("param error".equals(result.getMessage())){
                            closeProgressDialog();
                            Toast.makeText(imageSearch.this,"图片有误",Toast.LENGTH_SHORT).show();
                        } else if("Error image input".equals(result.getMessage())){
                            closeProgressDialog();
                            Toast.makeText(imageSearch.this,"图片有误",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //权限的申请结果返回
            case REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //已授权
                    Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
                } else {
                    //未授权
                    Toast.makeText(this, "授权被拒绝！", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }

    }

    private void turnOnCamera(){
        SimpleDateFormat timeStampFormat = new SimpleDateFormat("HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        //创建File对象
        outputImage = new File(getExternalCacheDir(), "takePhoto" + filename + ".jpg");
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(this,
                    "com.llw.goodtrash.fileprovider", outputImage);
        } else {
            imageUri = Uri.fromFile(outputImage);
        }
        //打开相机
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 3);

    }



    }
